import os
import json
from pathlib import Path
from typing import Dict, Any, List


class Storage:
    def __init__(self):
        self.config_dir = Path.home() / ".config" / "tomato-clock-cli"
        self.data_file = self.config_dir / "tasks.json"
        self._ensure_config_dir()

    def _ensure_config_dir(self):
        """确保配置目录存在"""
        self.config_dir.mkdir(parents=True, exist_ok=True)

    def _get_default_data(self) -> Dict[str, Any]:
        """返回默认的数据结构"""
        return {"tasks": [], "next_id": 1}

    def load_data(self) -> Dict[str, Any]:
        """加载任务数据"""
        if not self.data_file.exists():
            return self._get_default_data()

        try:
            with open(self.data_file, "r", encoding="utf-8") as f:
                return json.load(f)
        except (json.JSONDecodeError, IOError):
            return self._get_default_data()

    def save_data(self, data: Dict[str, Any]):
        """保存任务数据"""
        try:
            with open(self.data_file, "w", encoding="utf-8") as f:
                json.dump(data, f, ensure_ascii=False, indent=2)
        except IOError as e:
            raise Exception(f"无法保存数据: {e}")
